package cn.iocoder.yudao.module.vote.service.dept;

import cn.iocoder.yudao.module.vote.dal.mysql.voteuserresult.VoteUserResultMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.vote.controller.admin.dept.vo.*;
import cn.iocoder.yudao.module.vote.dal.dataobject.dept.VoteDeptDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.vote.convert.dept.VoteDeptConvert;
import cn.iocoder.yudao.module.vote.dal.mysql.dept.VoteDeptMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.vote.enums.ErrorCodeConstants.*;

/**
 * 部门信息 Service 实现类
 *
 * @author moving
 */
@Service
@Validated
public class VoteDeptServiceImpl implements VoteDeptService {

    @Resource
    private VoteDeptMapper voteDeptMapper;

    @Resource
    private VoteUserResultMapper userResultMapper;


    @Override
    public Long createDept(VoteDeptCreateReqVO createReqVO) {
        // 插入
        VoteDeptDO dept = VoteDeptConvert.INSTANCE.convert(createReqVO);
        voteDeptMapper.insert(dept);
        // 返回
        return dept.getId();
    }

    @Override
    public void updateDept(VoteDeptUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateDeptExists(updateReqVO.getId());
        // 更新
        VoteDeptDO updateObj = VoteDeptConvert.INSTANCE.convert(updateReqVO);
        voteDeptMapper.updateById(updateObj);
    }

    @Override
    public void deleteDept(Long id) {
        // 校验存在
        this.validateDeptExists(id);
        // 判断是否有引用

        Long count = userResultMapper.countByDeptId(id);
        if(count!=null && count>0){
            throw exception(DEPT_VOTE_RESULT_EXISTS);
        }
        // 删除
        voteDeptMapper.deleteById(id);
    }

    private void validateDeptExists(Long id) {
        if (voteDeptMapper.selectById(id) == null) {
            throw exception(DEPT_NOT_EXISTS);
        }
    }

    @Override
    public VoteDeptDO getDept(Long id) {
        return voteDeptMapper.selectById(id);
    }

    @Override
    public List<VoteDeptDO> getDeptList(Collection<Long> ids) {
        return voteDeptMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<VoteDeptDO> getDeptPage(VoteDeptPageReqVO pageReqVO) {
        return voteDeptMapper.selectPage(pageReqVO);
    }

    @Override
    public List<VoteDeptDO> getDeptList(VoteDeptExportReqVO exportReqVO) {
        return voteDeptMapper.selectList(exportReqVO);
    }


}
